<template>
  <div class="app-container">
    <transition name="el-zoom-in-top">
      <el-card v-if="showDetail"
               shadow="never">
        <div slot="header">
          <el-row>
            <el-col :span="24"
                    style=" text-align: center">
              <span>{{actionTitle}}</span>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-steps :active="activeStep"
                        simple>
                <el-step title="1 信息录入"
                         icon="el-icon-edit"
                         @click.native="gotoStep(1)"></el-step>
                <el-step title="2 确认提交"
                         icon="el-icon-check"
                         @click.native="gotoStep(2)"></el-step>
              </el-steps>
            </el-col>
          </el-row>
        </div>
        <div v-if="activeStep === 1">
          <el-row>
            <el-container>
              <el-col :span="8">
                <el-card class="my-contain-card"
                         shadow="never">
                  <el-tree ref="panelTree"
                           :data="treeData"
                           :props="defaultProps"
                           node-key="id"
                           default-expand-all
                           highlight-current
                           @current-change="currentChange"
                           @node-click="nodeClick"
                           :expand-on-click-node="false">
                    <!-- <span class="custom-tree-node"
                          slot-scope="{ node, data }">
                    <span>{{ node.label }}</span> -->
                  </el-tree>
                </el-card>
              </el-col>
              <el-col :span="16">
                <el-card class="my-contain-card"
                         shadow="never">
                  <transition name="el-zoom-in-top">
                    <div>
                      <el-form :model="tempEditPerm"
                               :rules="rules"
                               label-position="left"
                               ref="ruleForm"
                               label-width="100px">
                        <div v-show="tempEditPerm.permType === '1'">
                          <el-row>
                            <el-col :span="24">
                              <el-form-item label="面板标题"
                                            prop="title">
                                <el-input v-model="tempEditPerm.title"></el-input>
                              </el-form-item>
                            </el-col>
                          </el-row>
                          <el-row>
                            <el-col :span="24">
                              <el-form-item label="面板图标"
                                            prop="iconClass">
                                <el-input v-model="tempEditPerm.iconClass"
                                          :prefix-icon="tempEditPerm.iconClass"></el-input>
                              </el-form-item>
                            </el-col>
                          </el-row>
                          <el-row>
                            <el-col :span="24">
                              <el-form-item label="面板参数"
                                            prop="name">
                                <el-input v-model="tempEditPerm.name"></el-input>
                              </el-form-item>
                            </el-col>
                          </el-row>
                        </div>
                        <div v-show="tempEditPerm.permType === '0'">
                          <el-row>
                            <el-col :span="24">
                              <el-form-item label="功能名称"
                                            prop="title">
                                <el-input v-model="tempEditPerm.title"></el-input>
                              </el-form-item>
                            </el-col>
                            <el-col :span="24">
                              <el-form-item label="功能路径"
                                            prop="name">
                                <el-input v-model="tempEditPerm.name"></el-input>
                              </el-form-item>
                            </el-col>
                            <el-col :span="24">
                              <el-form-item label="功能参数"
                                            prop="parameters">
                                <el-select v-model="tempEditPerm.parameterIds"
                                           multiple
                                           placeholder="请选择"
                                           style="width:100%">
                                  <el-option v-for="item in getOptions('mandy_param_title')"
                                             :key="item.value"
                                             :label="item.label"
                                             :value="item.value">
                                  </el-option>
                                </el-select>
                              </el-form-item>
                            </el-col>
                          </el-row>
                        </div>
                        <el-row>
                          <el-form-item label="备注说明"
                                        prop="remark">
                            <el-input v-model="tempEditPerm.remark"
                                      type="textarea"
                                      :rows="2"></el-input>
                          </el-form-item>
                        </el-row>
                      </el-form>
                    </div>
                  </transition>
                </el-card>
              </el-col>
            </el-container>
          </el-row>
          <hr />
          <el-row>
            <el-button-group>
              <el-button type="primary"
                         size="medium"
                         plain
                         @click="handleNewFunction">新增</el-button>
              <el-button type="primary"
                         size="medium"
                         plain
                         :disabled="deleteButtonEnable"
                         @click="handleDeleteFunction">删除</el-button>
              <el-button type="success"
                         size="medium"
                         plain
                         @click="gotoStep(2)">下一步</el-button>
              <el-button type="danger"
                         size="medium"
                         plain
                         @click="userCancel">取消</el-button>
            </el-button-group>
          </el-row>
        </div>
        <div v-if="activeStep === 2">
          <el-card class="my-contain-card"
                   shadow="never">
            <el-row>
              <el-card shadow="never">
                <div slot="header"
                     class="clearfix bg-purple-light">
                  <el-row style="margin-bottom: 10px margin-top: 10px">
                    <el-col :span="24">
                      <el-input v-model="treeData[0].title"
                                :prefix-icon="treeData[0].iconClass">
                        <template :disabled="true"
                                  slot="prepend">面板标题：</template>
                      </el-input>
                    </el-col>
                  </el-row>
                  <el-row style="margin-bottom: 10px">
                    <el-col :span="24">
                      <el-input :disabled="true"
                                v-model="treeData[0].remark">
                        <template slot="prepend">备注说明：</template>
                      </el-input>
                    </el-col>
                  </el-row>
                  <el-row style="margin-bottom: 10px">
                    <el-col :span="3"
                            align="center">状态：
                    </el-col>
                    <el-col :span="21">
                      <el-switch v-model="treeData[0].auditState"
                                 :disabled="actionType != 2 "
                                 active-value="1"
                                 inactive-value="0"
                                 :active-text="getDictLabel('audit_state', '1')"
                                 :inactive-text="getDictLabel('audit_state', '0')">
                      </el-switch>
                    </el-col>
                  </el-row>
                </div>
                <el-row :gutter="10"
                        style="margin-bottom: 5px">
                  <el-col :span="4">
                    功能名称
                  </el-col>
                  <el-col :span="7">
                    功能路径
                  </el-col>
                  <el-col :span="13">
                    备注说明
                  </el-col>
                </el-row>
                <div v-for="child in treeData[0].children"
                     class="text item">
                  <el-row :gutter="10"
                          style="margin-bottom: 5px">
                    <el-col :span="4">
                      <el-input :disabled="true"
                                v-model="child.title">
                      </el-input>
                    </el-col>
                    <el-col :span="7">
                      <el-input :disabled="true"
                                v-model="child.name">
                      </el-input>
                      <el-tag v-for="param in child.parameterIds"
                              :key="param"
                              type="info">
                        {{ getDictLabel('mandy_param_title', param) }}
                      </el-tag>
                    </el-col>
                    <el-col :span="13">
                      <el-input :disabled="true"
                                v-model="child.remark">
                      </el-input>
                    </el-col>
                  </el-row>
                </div>
              </el-card>
            </el-row>
            <hr />
            <el-button-group>
              <el-button type="danger"
                         size="medium"
                         plain
                         @click="userCancel">取消</el-button>
              <el-button type="success"
                         size="medium"
                         plain
                         @click="commitForm">确认提交</el-button>
            </el-button-group>
          </el-card>
        </div>
      </el-card>
    </transition>
    <el-card shadow="hover">
      <el-input v-model="listQuery.title"
                placeholder="标题"
                size="small"
                style="width: 200px;"
                class="filter-item" />
      <el-select v-model="listQuery.auditState"
                 placeholder="状态"
                 clearable
                 size="small"
                 style="width: 90px"
                 class="filter-item">
        <el-option v-for="item in getDictLabel('audit_state')"
                   :key="item.value"
                   :label="item.label"
                   :value="item.value" />
      </el-select>
      <el-button @click="handleListPanel"
                 class="filter-item"
                 plain
                 size="small"
                 type="primary"
                 icon="el-icon-search">
        查询
      </el-button>
    </el-card>
    <el-card shadow="never">
      <el-table v-loading="listLoading"
                :data="dataList"
                border
                fit
                highlight-current-row
                style="width: 100%;">
        <el-table-column label="行号"
                         type="index"
                         sortable
                         align="center"
                         width="80">
        </el-table-column>
        <el-table-column label="标题"
                         width="180px"
                         align="center">
          <template slot-scope="{ row }">
            <i :class="row.iconClass"></i>
            <span> {{ row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态"
                         width="80px"
                         align="left">
          <template slot-scope="{ row }">
            <span> {{ getDictLabel('audit_state',row.auditState)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="面板组件名"
                         prop="name"
                         width="150px"
                         align="center">
        </el-table-column>
        <el-table-column label="备注"
                         prop="remark"
                         align="left">
        </el-table-column>
        <el-table-column label="操作"
                         align="center"
                         width="150px"
                         class-name="small-padding fixed-width">
          <template slot-scope="{ row }">
            <el-tooltip v-if="hasPermission('/sysadmin/panel/copy')"
                        class="item"
                        effect="light"
                        content="复制面板"
                        placement="top-start">
              <el-button :disabled="showDetail"
                         size="mini"
                         type="primary"
                         icon="el-icon-copy-document"
                         circle
                         @click="handleUpdate(row,0)">
              </el-button>
            </el-tooltip>
            <el-tooltip v-if="hasPermission('/sysadmin/panel/update')"
                        class="item"
                        effect="light"
                        content="修改面板"
                        placement="top">
              <el-button :disabled="disabledUpdateBotton(row)"
                         size="mini"
                         type="warning"
                         icon="el-icon-edit"
                         circle
                         @click="handleUpdate(row,1)">
              </el-button>
            </el-tooltip>
            <el-tooltip v-if="hasPermission('/sysadmin/panel/audit')"
                        class="item"
                        effect="light"
                        content="禁用启用面板"
                        placement="top-end">
              <el-button :disabled="showDetail"
                         size="mini"
                         type="success"
                         icon="el-icon-s-check"
                         circle
                         @click="handleUpdate(row,2)">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { apiPanelList, apiPanelCopy, apiPanelUpdate, apiPanelAudit } from "@/api/sysadmin";
import { getMinId } from "@/api/CommonUtil";
import { getLabel, getEntries, hasPermission } from "@/utils/dict";

export default {
  name: "MandyPanel",
  data() {
    return {
      interval: null,
      isMoving: false,
      //data: JSON.parse(JSON.stringify(data)), 
      defaultProps: {
        children: 'children',
        label: 'title'
      },

      blandNewFunction: {
        createUserId: 0,
        iconClass: '',
        id: 0,
        lastModifyTime: 0,
        name: '',
        parentId: 0,
        permType: '0',
        remark: '',
        auditState: '',
        title: ''
      },

      treeData: [],
      tempEditId: null,
      tempEditPerm: null,
      editEnable: false,
      showDetail: false,
      deleteButtonEnable: true,
      actionType: 0,
      activeStep: 1,
      dataList: null,
      total: 0,
      listLoading: false,
      listQuery: {
        auditState: undefined,
        title: undefined
      },

      rules: {
        title: [
          {
            required: true,
            message: "请输入面板标题",
            trigger: "blur"
          },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur"
          }
        ],
        name: [
          {
            required: true,
            message: "必须输入项,系统会作为内部参数使用",
            trigger: "blur"
          },
          {
            min: 2,
            max: 60,
            message: "长度在 2 到 60 个字符",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    //this.getDataList();
  },

  computed: {
    actionTitle() {
      switch (this.actionType) {
        case 0:
          return "新增面板"
          break;
        case 1:
          return "修改面板"
          break;
        case 2:
          return "审核面板"
          break;
        default:
          return "SORRY"
      }
    },
  },

  mounted() {
    window.addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll)
    if (this.interval) {
      clearInterval(this.interval)
    }
  },

  methods: {
    ...mapGetters([
      'dictMap'
    ]),

    hasPermission(url) {
      return hasPermission(url)
    },

    messageSuccess() {
      this.$message({
        type: 'success',
        message: '提交成功!',
        duration: 3000
      });
    },

    userCancel() {
      this.$confirm('检测到有未保存的内容，是否在离开页面，放弃保存？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.showDetail = false;
        this.activeStep = 1;
      });
    },

    disabledUpdateBotton(row) {
      if (this.showDetail || row.auditState === '1') {
        return true;
      }
      return false;
    },

    handleDeleteFunction() {
      let deleteId = this.$refs.panelTree.currentNode.node.data.id;
      let panelId = this.treeData[0].id;
      this.tempEditPerm = this.treeData[0];
      const children = this.treeData[0].children;
      const index = children.findIndex(d => d.id === deleteId);
      children.splice(index, 1);
      this.$refs.panelTree.setCurrentKey(panelId);
      this.deleteButtonEnable = true;
    },

    handleNewFunction() {
      const children = this.treeData[0].children;
      let tmpItem = Object.assign({}, this.blandNewFunction);
      tmpItem.id = getMinId(this.treeData) - 1;
      tmpItem.parentId = this.treeData[0].id;
      tmpItem.title = '新功能';

      children.push(tmpItem);
      //let panelId = tmpItem.id;
      //this.$refs.panelTree.setCurrentKey(panelId); 奇怪跳不到新结点
      //面板节点则可以
      this.$refs.panelTree.setCurrentKey(this.treeData[0].id);
    },

    commitForm() {
      this.listLoading = true;
      this.$confirm('是否确认提交保存当前操作？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.actionType === 0) {
          this.callPanelCopy();
        } else if (this.actionType === 1) {
          this.callPanelUpdate();
        } else {
          this.callPanelAudit();
        }
      });
      console.log("this.listLoading = false;");
      this.listLoading = false;
    },

    callPanelCopy() {
      apiPanelCopy(this.treeData[0]).then(response => {
        this.showDetail = false;
        const data = response.data;
        this.dataList.push(data);
        this.messageSuccess();

      });

    },

    updateDataList(data) {
      for (let i = 0, len = this.dataList.length; i < len; i++) {
        if (data.id === this.dataList[i].id) {
          this.dataList[i] = data;
        }
      }
    },

    callPanelUpdate() {
      apiPanelUpdate(this.treeData[0]).then(response => {
        this.showDetail = false;
        const data = response.data;
        this.updateDataList(data);
        this.messageSuccess();
      });
    },

    callPanelAudit() {
      apiPanelAudit(this.treeData[0]).then(response => {
        this.showDetail = false;
        const data = response.data;
        //this.dataList.push(data);
        this.updateDataList(data);
        this.messageSuccess();
      });
    },


    currentChange(data, node) {
      this.tempEditPerm = data;
      if (this.tempEditPerm.permType === "0") {
        this.deleteButtonEnable = false;
      } else {
        this.deleteButtonEnable = true;
      }
    },
    nodeClick() {
      //
    },

    handleListPanel() {
      this.listLoading = true;
      apiPanelList(this.listQuery)
        .then(response => {
          this.listLoading = false;
          const data = response.data;
          if (data) {
            this.dataList = data;
          }
        });
      this.listLoading = false;
    },

    getOptions(dictKey) {
      return getEntries(dictKey);
    },

    getDictLabel(dictKey, dictValue) {
      return getLabel(dictKey, dictValue);
    },

    handleFilter() { },
    handleUpdate(row, actionType) {
      if (this.showDetail) {
        this.$alert('请先提交或取消当前操作', '提示', {
          confirmButtonText: '确定',
          callback: action => { }
        });
        return;
      }

      if (actionType === 1 && row.auditState === '1') {
        this.$alert('已经在启用的面板不允许修改!', '提示', {
          confirmButtonText: '确定',
          callback: action => { }
        });
        return;
      }

      this.treeData = [];
      this.deleteButtonEnable = true;
      //this.tempEditPerm = Object.assign({}, row);
      this.treeData.push(Object.assign({}, row));
      this.tempEditPerm = this.treeData[0];
      this.actionType = actionType;

      if (actionType === 2) {
        this.activeStep = 2;
        this.editEnable = false;
      } else {
        this.tempEditPerm.auditState = '0';
        this.editEnable = true;
        this.activeStep = 1;
      }
      this.showDetail = true;

      this.backToTop();
    },
    gotoStep(stepNbr) {
      if (stepNbr === 1 && this.editEnable) {
        this.activeStep = 1;
      } else if (stepNbr === 2 && this.activeStep === 1) {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.activeStep = 2;
          } else {
            console.log('参数验证不合法！');
          }
        })
      }
    },
    easeInOutQuad(t, b, c, d) {
      if ((t /= d / 2) < 1) return c / 2 * t * t + b
      return -c / 2 * (--t * (t - 2) - 1) + b
    },
    backToTop() {
      if (this.isMoving) return
      const start = window.pageYOffset
      let i = 0
      this.isMoving = true
      this.interval = setInterval(() => {
        const next = Math.floor(this.easeInOutQuad(10 * i, start, -start, 500))
        if (next <= 50) {
          window.scrollTo(0, 50)
          clearInterval(this.interval)
          this.isMoving = false
        } else {
          window.scrollTo(0, next)
        }
        i++
      }, 16.7)
    },
  }
};
</script>
<style scoped>
.el-tree {
  width: 100%;
  height: 100%;
}

.my-contain-card {
  padding: 2px;
  width: 100%;
  height: 100%;
}
.el-tree > .el-tree-node {
  display: inline-block;
  min-width: 100%;
}
.bg-purple-light {
  background: #e5e9f2;
}
</style>

